<?php

namespace app\api\controller;

use alibaba\Check;
use app\common\controller\Api;
use Exception;
use fast\Ecar;
use think\Db;
use think\exception\PDOException;
use wxApp\WxApp;

/**
 * 首页接口
 */
class Car extends Api
{

    protected $noNeedLogin = ['car_old_detail','car_sparkle_list','car_old_list','car_label_list','automatic_delisting',
        'circle_info_delisting','car_selection_list','car_old_detail','car_modes_detail','car_modes_all_parameter',
        'brand_list','car_series_list','car_modes_list'];
    protected $noNeedRight = ['*'];

    //vin
    public function get_vin() {
        $vin = input("vin");
        if (empty($vin)) {
            $this->error("vin不能为空");
        }
        $ecar = new  Ecar;
        $this->success('请求成功',$ecar->getVIN($vin));
    }

    //行驶证
    public function get_ocr() {
        $imageUrl= input("imageUrl");
        if (empty($imageUrl)) {
            $this->error("图片地址不能为空");
        }
        $ecar = new  Ecar;
        $this->success('请求成功',$ecar->getOCR($imageUrl));
    }

    //国别列表
    public function car_brand_type_list() {

        $list = Db::name("car_brand_type")
            ->where("status",1)
            ->select();
        $this->success('请求成功',$list);
    }

    //品牌列表
    public function brand_list() {
        $keyword = input("keyword");
        $name = input("name");
        if (!empty($name)) {
            $keyword =  $name;
        }
        $ecar = new  Ecar;
        $this->success('请求成功',$ecar->getMasterBrand($keyword));
    }

    //车系列表
    public function car_series_list() {

        $brand_id = input("brand_id");
        $keyword = input("keyword");
        $name = input("name");
        if (!empty($name)) {
            $keyword =  $name;
        }

        $ecar = new  Ecar;
        $this->success('请求成功',$ecar->getSerial($brand_id,$keyword));
    }

    //车型列表
    public function car_modes_list() {

        $series_id = input("series_id");
        $keyword = input("keyword");
        $name = input("name");
        if (!empty($name)) {
            $keyword =  $name;
        }
        $ecar = new  Ecar;
        $this->success('请求成功',$ecar->getModel($series_id,$keyword));
    }

    //车型 详细参数
    public function car_modes_detail() {

        $modes_id = input("modes_id");

        $ecar = new  Ecar;
        $this->success('请求成功',$ecar->getModelDetail($modes_id));
    }

    //车型 详细配置
    public function car_modes_all_parameter() {

        $modes_id = input("modes_id");

        $ecar = new  Ecar;
        $this->success('请求成功',$ecar->getModelAllParameter($modes_id));
    }

    //亮点列表
    public function car_sparkle_list() {

        $list = Db::name("car_sparkle")
            ->where("status",1)
            ->select();
        $this->success('请求成功',$list);
    }

    //标签列表
    public function car_label_list() {

        $type = input("type");
        $list = Db::name("car_label");
        if (!empty($type)) {
            $list = $list->where("type",$type);
        }
        $list = $list->where("status",1)
            ->select();
        $this->success('请求成功',$list);
    }

    //快速选车
    public function car_selection_list() {

        $list = Db::name("car_selection")
            ->where("status",1)
            ->order("id")
            ->select();
        $this->success('请求成功',$list);
    }

    //车源筛选条件
    public function getCarOld(){
        $list = Db::name("car_old");

        //模糊查询
        $param = input("search");
        if (!empty($param)) {
            $list = $list->where("car_brand_name|car_series_name|car_models_name|id","like","%$param%");
        }


        //车辆级别
        $param= input("get.car_level/a");
        if (!empty($param)) {
            $list = $list->whereIn("car_level",$param);
        }

        //品牌
        $car_brand_id = input("car_brand_id");
        if (!empty($car_brand_id)) {
            $list = $list->where("car_brand_id",$car_brand_id);
        }

        //车系
        $car_series_id = input("car_series_id");
        if (!empty($car_series_id)) {
            $list = $list->where("car_series_id",$car_series_id);
        }


        //车型
        $car_models_id = input("car_models_id");
        if (!empty($car_models_id)) {
            $list = $list->where("car_models_id",$car_models_id);
        }

        //车型名称
//        $car_models_name = input("car_models_name");
//        if (!empty($car_models_name)) {
//            $list = $list->where("car_models_name", 'LIKE', "%$car_models_name%");
//        }

        //品牌s
        $param = input("car_brand_ids/a");
        if (!empty($param)) {
            $list = $list->where("car_brand_id","in",$param);
        }

        //车系s
        $param = input("car_series_ids/a");
        if (!empty($param)) {
            $list = $list->where("car_series_id","in",$param);
        }

        //车型s
        $param = input("car_models_ids/a");
        if (!empty($param)) {
            $list = $list->where("car_models_id","in",$param);
        }


        //有检测
        $param = input("test_report_file");
        if ($param == 1 ) {
            $list = $list->where("test_report_file","<>","");
        }

        //再降价
        $param = input("cut_price");
        if ($param == 1 ) {
            $list = $list->where("cut_price > price");
        }

        //一首车
        $param = input("transfer_num");
        if ($param == 1 ) {
            $list = $list->where("transfer_num",0);
        }



        //推荐
        $param = input("recommend");
        if ($param == 1) {
            $list = $list->where("recommend",$param);
        }

        //热搜
        $param = input("hot_search");
        if ($param == 1) {
            $list = $list->where("hot_search",$param);
        }

        //热销
        $param = input("hot_sales");
        if ($param == 1) {
            $list = $list->where("hot_sales",$param);
        }

        //车辆分类 0二手车 1新车
        $param = input("type");
        if (!empty($param)) {
            $list = $list->where("type",$param);
        }

        //是否一口价:  1 是 ,0否 ，空 不限
        $param = input("is_price");
        if (!empty($param)) {
            $list = $list->where("is_price",$param);
        }

        //国别id
        $param = input("car_brand_type_id/a");
        if (!empty($param)) {
            $list = $list->where("car_brand_type_id","in",$param);
        }

        //车龄
        $param= input("get.car_age/a");
        if (!empty($param)) {
            if (count($param)>0) {
                $param = explode(",", $param[0]);
                if ($param[0] > 0) {
                    $future_time = date('Y-m-d', strtotime("-$param[0] year"));
                    $list = $list->where("factory_date","<=",$future_time);
                }

                if ($param[1] > 0) {
                    $future_time = date('Y-m-d', strtotime("-$param[1] year"));
                    $list = $list->where("factory_date",">=",$future_time);
                }
            }


        }

        //车龄
        $param= input("get.car_chuchang/a");
        if (!empty($param)) {
            if (count($param)>0) {
                $param = explode(",", $param[0]);
                if ($param[0] > 0) {
                    $future_time = date('Y-m-d', strtotime("-$param[0] year"));
                    $list = $list->where("registration_time","<=",$future_time);
                }

                if ($param[1] > 0) {
                    $future_time = date('Y-m-d', strtotime("-$param[1] year"));
                    $list = $list->where("registration_time",">=",$future_time);
                }
            }


        }

        //价格
        $param= input("get.price/a");
        if (!empty($param)) {
            if (count($param)>0) {
                $param = explode(",", $param[0]);
                if ($param[0] > 0) {
                    $list = $list->where("price",">=",$param[0]);
                }
                if ($param[1] > 0) {
                    $list = $list->where("price","<=",$param[1]);
                }
            }


        }

        //里程
        $param= input("get.odometer_km/a");
        if (!empty($param)) {
            if (count($param)>0) {
                $param = explode(",", $param[0]);
                if ($param[0] > 0) {
                    $list = $list->where("odometer_km",">=",$param[0]);
                }
                if ($param[1] > 0) {
                    $list = $list->where("odometer_km","<=",$param[1]);
                }
            }



        }

        //排量
        $param= input("get.cc/a");
        if (!empty($param)) {
            if (count($param)>0) {
                $param = explode(",", $param[0]);
                if ($param[0] > 0) {
                    $list = $list->where("cc",">=",$param[0]);
                }
                if ($param[1] > 0) {
                    $list = $list->where("cc","<=",$param[1]);
                }
            }


        }

        //车身颜色
        $param= input("get.car_colour/a");
        if (!empty($param)) {
            $list = $list->whereIn("car_colour",$param);
        }

        //国别
        $param= input("get.car_brand_type_id/a");
        if (!empty($param)) {
            $list = $list->whereIn("car_brand_type_id",$param);
        }

        //变速箱
        $param= input("get.gearbox/a");
        if (!empty($param)) {
            $list = $list->whereIn("gearbox",$param);
        }

        //排放标准
        $param= input("get.FES/a");
        if (!empty($param)) {
            $list = $list->whereIn("FES",$param);
        }

        //能源类型
        $param= input("get.energy_type/a");
        if (!empty($param)) {
            $list = $list->whereIn("energy_type",$param);
        }

        //驱动形式
        $param= input("get.drive_type/a");
        if (!empty($param)) {
            $list = $list->whereIn("drive_type",$param);
        }

        //车身结构
        $param= input("get.body_structure/a");
        if (!empty($param)) {
            $list = $list->whereIn("body_structure",$param);
        }

        //车源标签
        $param= input("get.label_ids/a");
        if (!empty($param)) {


            $val = implode("|", $param);
            //CONCAT (',',gameIds,',') REGEXP ',(155|10),'
            $list = $list->where("CONCAT (',',label_ids,',') REGEXP ',$val,'");

//            foreach ($param as $v) {
//                $list = $list->whereOr('FIND_IN_SET('.$v.',label_ids)');
//            }
        }

        //所在地
        $param= input("get.city/a");
        if (!empty($param)) {
            foreach ($param as $key=>$value){
                if (empty($value)){
                    unset($param[$key]);
                }
            }
            if (count($param) > 0) {
                $val = implode("|", $param);

                $list = $list->where("city REGEXP '[,|;]?".$val."[,|;]?'");
            }
        }


        //车源编码
        $param = input("id");
        if ($param != "" ) {
            $list = $list->where("id",$param);
        }





        return $list;
    }
    //车源列表
    public function car_old_list() {

        $list = $this->getCarOld();


        $id = input("id");
        if (!empty($id)) {
            $list = $list->where("id",$id);
        }

        $user_id = input("user_id");
        if (!empty($user_id)) {
            $list = $list->where("user_id",$user_id);
        }
        //本人显示所有
        if ($this->auth->id == $user_id && !empty($this->auth->id) && !empty($user_id)) {
            $status = input("status");
            if ($status != "") {
                $list = $list->where("status",$status);
            }

            $verify_status = input("verify_status");
            if ($verify_status != "") {
                $list = $list->where("verify_status",$verify_status);
            }

        } else {
            $list =  $list->where("status",1)
                ->where("trade_status",1)
                ->where("verify_status",1);
        }

        //排序
        $sort = input("sort");
        $order = input("order");
        if (empty($sort)){
            $list =  $list->order("weight desc")->orderRaw("CASE WHEN FROM_UNIXTIME(createtime, '%Y-%m-%d') = CURDATE() THEN 1 WHEN cut_price > price THEN 2 ELSE 3 END ASC")->order("createtime desc");
        } else {
            $list =  $list->order($sort,$order);
        }
        //分页
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page-1)*$limit;
        $list =  $list->limit("$offset,$limit")
            ->select();
//        echo Db::getLastSql();
        $this->success('请求成功',$list);
    }


    //我的车源列表
    public function my_car_old_list() {

        $list = $this->getCarOld();


        $id = input("id");
        if (!empty($id)) {
            $list = $list->where("id",$id);
        }


        $list = $list->where("user_id",$this->auth->id);

        $status = input("status");
        if ($status != "") {
            $list = $list->where("status",$status);
        }

        $verify_status = input("verify_status");
        if ($verify_status != "") {
            $list = $list->where("verify_status",$verify_status);
        }


        //排序
        $sort = input("sort");
        $order = input("order");
        if (empty($sort)){
            $list =  $list->order("weight desc")->orderRaw("CASE WHEN FROM_UNIXTIME(createtime, '%Y-%m-%d') = CURDATE() THEN 1 WHEN cut_price > price THEN 2 ELSE 3 END ASC")->order("createtime desc");
        } else {
            $list =  $list->order($sort,$order);
        }
        //分页
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page-1)*$limit;
        $list =  $list->limit("$offset,$limit")
            ->select();
//        echo Db::getLastSql();
        $this->success('请求成功',$list);
    }


    //我的车源 统计
    public function car_old_count() {

        //在售
        $detail["value1"] = Db::name("car_old")->where("status",1)->where("user_id",$this->auth->id)->count();

        //待审核
        $detail["value2"] = Db::name("car_old")->where("verify_status",0)->where("user_id",$this->auth->id)->count();

        //未通过
        $detail["value3"] = Db::name("car_old")->where("verify_status",2)->where("user_id",$this->auth->id)->count();

        //下架的
        $detail["value4"] = Db::name("car_old")->where("status",0)->where("user_id",$this->auth->id)->count();

        $this->success('请求成功',$detail);
    }


    //删除车源
    public function car_old_del() {
        $params = input("id");
        $result = Db::name("car_old")
            ->where("id",$params)
            ->where("user_id",$this->auth->id)
            ->delete();
        $this->success("删除成功",$result);
    }

    //发布车源
    public function car_add()
    {

        $params = input("post.");

        if (empty($params["registration_time"])) {
            unset($params["registration_time"]);
        }

        if (empty($params["year_inspect_date"])) {
            unset($params["year_inspect_date"]);
        }

        if (empty($params["compulsory_insurance_date"])) {
            unset($params["compulsory_insurance_date"]);
        }
//        $params["verify_status"] = 1;
//        $params["status"] = 1;
        $params["verify_status"] = 0;
        $params["status"] = 0;
        $params["updatetime"] = time();
        $params["createtime"] = time();
        $params["user_id"] = $this->auth->id;

        //验证车源是否存在
        $rs = Db::name("car_old")->where("VIN",$params["VIN"])->find();
        if (!empty($rs)) {

            if ($this->auth->id == $rs["user_id"]){
                $this->error("车源已存在，无需重复录入");
            } else{
                if ($rs["status"] == 1) {
                    $this->error("车源已在他人名下,无法录入",null,2);
                }
            }

        }

        //字典收集
        $this->dict_collect($params);


        //车辆图片
//        if (!empty($params["car_image"])) {
//         $car_images =  explode(",", $params["car_image"]);
//         foreach ($car_images as $k=>$v ) {
//            $req = (new Check)->imageCheck("https://oss.taochewa.com".$v);
//            if (!empty($req)) {
//                $i = $k+1;
//                $this->error("车辆图片第".$i."张，存在违规");
//            }
//         }
//        }

        //车辆铭牌
//        if (!empty($params["prove_image"])) {
//            $car_images =  explode(",", $params["prove_image"]);
//            foreach ($car_images as $k=>$v ) {
//                $req = (new Check)->imageCheck("https://oss.taochewa.com".$v);
//                if (!empty($req)) {
//                    $i = $k+1;
//                    $this->error("车辆铭牌图片第".$i."张，存在违规");
//                }
//            }
//        }

//        //检测报告
//        if (!empty($params["test_report_file"])) {
//            $car_images =  explode(",", $params["test_report_file"]);
//            foreach ($car_images as $k=>$v ) {
//                $req = (new Check)->imageCheck("https://oss.taochewa.com".$v);
//                if (!empty($req)) {
//                    $i = $k+1;
//                    $this->error("检测报告图片第".$i."张，存在违规");
//                }
//            }
//        }


//        //4s店记录
//        if (!empty($params["ssss_report_image"])) {
//            $car_images =  explode(",", $params["ssss_report_image"]);
//            foreach ($car_images as $k=>$v ) {
//                $req = (new Check)->imageCheck("https://oss.taochewa.com".$v);
//                if (!empty($req)) {
//                    $i = $k+1;
//                    $this->error("4S店记录图片第".$i."张，存在违规");
//                }
//            }
//        }

//        //出险记录
//        if (!empty($params["danger_report_image"])) {
//            $car_images =  explode(",", $params["danger_report_image"]);
//            foreach ($car_images as $k=>$v ) {
//                $req = (new Check)->imageCheck("https://oss.taochewa.com".$v);
//                if (!empty($req)) {
//                    $i = $k+1;
//                    $this->error("出险记录图片第".$i."张，存在违规");
//                }
//            }
//        }



        //文字检验
        if (!empty($params["car_describe"])) {
            $req = (new Check)->textCheck($params["car_describe"]);
            if (!empty($req)) {
                $this->error("车辆描述，存在”".$req."“内容");
            }
        }



        $result = false;
        Db::startTrans();
        try {
            if (!empty($params["car_video"]) || !empty($params["yanche_video"])) {
                $params["verify_status"] = 0;
                $params["status"] = 0;
            }
            $result = Db::name("car_old")->insertGetId($params);

            //验车视频
            if (!empty($params["yanche_video"])) {
                $req = (new Check)->videoCheck("https://oss.taochewa.com".$params["yanche_video"]);
                if (!empty($req)) {
                    Db::name("car_old_video_review")->insert([
                        "car_old_id"=>$result,
                        "taskId"=>$req
                    ]);
                }
            }
            //车辆视频
            if (!empty($params["car_video"])) {
                $req = (new Check)->videoCheck("https://oss.taochewa.com".$params["car_video"]);
                if (!empty($req)) {
                    Db::name("car_old_video_review")->insert([
                        "car_old_id"=>$result,
                        "taskId"=>$req
                    ]);
                }
            }



            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($result === false) {
            $this->error("发布失败");
        }
        $this->success("发布成功");
    }

    //字典收集
    public function dict_collect ($params) {
        try {
            //国别
            if (isset($params["guobie"]) && !empty($params["guobie"])) {
                $res = Db::name("car_dict")->where("type",1)->where("name", $params["guobie"])->find();
                if (empty($res)) {
                    Db::name("car_dict")->insert([
                        "name" => $params["guobie"],
                        "type" => 1
                    ]);
                }
            }

            //车辆级别
            if (isset($params["car_level"]) && !empty($params["car_level"])) {
                $res = Db::name("car_dict")->where("type",2)->where("name", $params["car_level"])->find();
                if (empty($res)) {
                    Db::name("car_dict")->insert([
                        "name" => $params["car_level"],
                        "type" => 2
                    ]);
                }
            }

            //变速箱
            if (isset($params["gearbox"]) && !empty($params["gearbox"])) {
                $res = Db::name("car_dict")->where("type",3)->where("name", $params["gearbox"])->find();
                if (empty($res)) {
                    Db::name("car_dict")->insert([
                        "name" => $params["gearbox"],
                        "type" => 3
                    ]);
                }
            }

            //排放标准
            if (isset($params["FES"]) && !empty($params["FES"])) {
                $res = Db::name("car_dict")->where("type",4)->where("name", $params["FES"])->find();
                if (empty($res)) {
                    Db::name("car_dict")->insert([
                        "name" => $params["FES"],
                        "type" => 4
                    ]);
                }
            }

            //5驱动形式
            if (isset($params["drive_type"]) && !empty($params["drive_type"])) {
                $res = Db::name("car_dict")->where("type",5)->where("name", $params["drive_type"])->find();
                if (empty($res)) {
                    Db::name("car_dict")->insert([
                        "name" => $params["drive_type"],
                        "type" => 5
                    ]);
                }
            }

            //6车身结构
            if (isset($params["struct"]) && !empty($params["struct"])) {
                $res = Db::name("car_dict")->where("type",6)->where("name", $params["struct"])->find();
                if (empty($res)) {
                    Db::name("car_dict")->insert([
                        "name" => $params["struct"],
                        "type" => 6
                    ]);
                }
            }

        } catch (Exception $e) {

        }
    }

    //修改车源
    public function car_edit()
    {

        $params = input("post.");

        if (empty($params["registration_time"])) {
            unset($params["registration_time"]);
        }

        if (empty($params["year_inspect_date"])) {
            unset($params["year_inspect_date"]);
        }

        if (empty($params["compulsory_insurance_date"])) {
            unset($params["compulsory_insurance_date"]);
        }


//        if (empty($params["VIN"])) {
//            $this->error("VIN码不能为空");
//        }

        $params["verify_status"] = 0;

        //$params["status"] = 0;
        $params["updatetime"] = time();

        //验证车源是否存在
        $rs = Db::name("car_old")->where("VIN",$params["VIN"])->where("user_id","<>",$this->auth->id)->find();
        if (!empty($rs)) {
            if ($rs["status"] == 1) {
                $this->error("车源已在他人名下,无法录入",null,2);
            }

        }


//        //车辆图片
//        if (!empty($params["car_image"])) {
//            $car_images =  explode(",", $params["car_image"]);
//            foreach ($car_images as $k=>$v ) {
//                $req = (new Check)->imageCheck("https://oss.taochewa.com".$v);
//                if (!empty($req)) {
//                    $i = $k+1;
//                    $this->error("车辆图片第".$i."张，存在违规");
//                }
//            }
//        }

        //车辆铭牌
//        if (!empty($params["prove_image"])) {
//            $car_images =  explode(",", $params["prove_image"]);
//            foreach ($car_images as $k=>$v ) {
//                $req = (new Check)->imageCheck("https://oss.taochewa.com".$v);
//                if (!empty($req)) {
//                    $i = $k+1;
//                    $this->error("车辆铭牌图片第".$i."张，存在违规");
//                }
//            }
//        }

        //检测报告
//        if (!empty($params["test_report_file"])) {
//            $car_images =  explode(",", $params["test_report_file"]);
//            foreach ($car_images as $k=>$v ) {
//                $req = (new Check)->imageCheck("https://oss.taochewa.com".$v);
//                if (!empty($req)) {
//                    $i = $k+1;
//                    $this->error("检测报告图片第".$i."张，存在违规");
//                }
//            }
//        }

        //4s店记录
//        if (!empty($params["ssss_report_image"])) {
//            $car_images =  explode(",", $params["ssss_report_image"]);
//            foreach ($car_images as $k=>$v ) {
//                $req = (new Check)->imageCheck("https://oss.taochewa.com".$v);
//                if (!empty($req)) {
//                    $i = $k+1;
//                    $this->error("4S店记录图片第".$i."张，存在违规");
//                }
//            }
//        }

        //出险记录
//        if (!empty($params["danger_report_image"])) {
//            $car_images =  explode(",", $params["danger_report_image"]);
//            foreach ($car_images as $k=>$v ) {
//                $req = (new Check)->imageCheck("https://oss.taochewa.com".$v);
//                if (!empty($req)) {
//                    $i = $k+1;
//                    $this->error("出险记录图片第".$i."张，存在违规");
//                }
//            }
//        }


        //文字检验
        if (!empty($params["car_describe"])) {
            $req = (new Check)->textCheck($params["car_describe"]);
            if (!empty($req)) {
                $this->error("车辆描述，存在”".$req."“内容");
            }
        }


        $result = false;
        Db::startTrans();
        try {
            $id = $params["id"];
            unset($params["id"]);

//            if (!empty($params["car_video"]) || !empty($params["yanche_video"])) {
//                $params["verify_status"] = 0;
//                $params["status"] = 0;
//            }

            $result = Db::name("car_old")->where("user_id",$this->auth->id)->where("id",$id)->update($params);

            //验车视频
            if (!empty($params["yanche_video"])) {
                $req = (new Check)->videoCheck("https://oss.taochewa.com".$params["yanche_video"]);
                if (!empty($req)) {
                    Db::name("car_old_video_review")->insert([
                        "car_old_id"=>$result,
                        "taskId"=>$req
                    ]);
                }
            }
            //车辆视频
            if (!empty($params["car_video"])) {
                $req = (new Check)->videoCheck("https://oss.taochewa.com".$params["car_video"]);
                if (!empty($req)) {
                    Db::name("car_old_video_review")->insert([
                        "car_old_id"=>$result,
                        "taskId"=>$req
                    ]);
                }
            }


            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("发布失败");
        }
        $this->success("发布成功");
    }

    //车源修改价格
    public function car_edit_price()
    {

        $price = input("post.price");
        $base_price = input("post.base_price");
        $id = input("post.id");
        //$cut_price = input("post.cut_price");

        $result = false;
        Db::startTrans();
        try {
            $car = Db::name("car_old")->where("user_id",$this->auth->id)->where("id",$id)->find();
            $result = Db::name("car_old")->where("user_id",$this->auth->id)->where("id",$id)->update([
                "price"=>$price,
                "base_price"=>$base_price,
                "cut_price"=>$car["price"],
                "updatetime"=>time(),
            ]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("发布失败");
        }
        $this->success("发布成功");
    }

    //车源 上架下架
    public function car_edit_status()
    {

        $status = input("post.status");
        $id = input("post.id");
        $purchase_price = input("post.purchase_price");
        $pulled_reason = input("post.pulled_reason");

        $detail = Db::name("car_old")
            ->where("id",$id)
            ->find();

        if ($detail["verify_status"] != 1) {
            $this->error("未通过审核车源，无法操作");
        }

        //验证车源是否存在
        $rs = Db::name("car_old")->where("VIN",$detail["VIN"])->where("user_id","<>",$this->auth->id)->find();
        if (!empty($rs)) {
            if ($rs["status"] == 1) {
                $this->error("车源已在他人名下,无法上架",null,2);
            }

        }


        $result = false;
        Db::startTrans();
        try {
            $result = Db::name("car_old")->where("user_id",$this->auth->id)->where("id",$id)->update([
                "status"=>$status,
                "purchase_price"=>$purchase_price,
                "pulled_reason"=>$pulled_reason,
                "updatetime"=>time(),
            ]);

            if ($status == 1) {
                $result = Db::name("car_old")->where("user_id",$this->auth->id)->where("id",$id)->update([
                    "createtime"=>time(),
                ]);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("发布失败");
        }
        $this->success("发布成功");
    }

    //车源详情
    public function car_old_detail() {
        $id = input("id");

        $detail = Db::name("car_old")
            ->where("id",$id)
            ->find();
        $vip = Db::name("user_level")->where("id",1)->find();
        $detail["deposit"] = $vip["deposit"];
        //是否收藏
        $detail["is_collection"] = Db::name("car_collection")->where("user_id",$this->auth->id)->where("car_old_id",$id)->count();

        $this->success('请求成功',$detail);
    }

    //帮他下架
    public function help_lower_add()
    {

        $car_old_id = input("post.car_old_id");
        $notes = input("post.notes");
        if (empty($car_old_id) || empty($notes)) {
            $this->error("参数不能为空");
        }

        $params["car_old_id"] = $car_old_id;
        $params["notes"] = $notes;
        $params["createtime"] = time();
        $params["user_id"] = $this->auth->id;
        $result = Db::name("car_old_help_lower")->insert($params);
        if ($result) {

            $user_id  = input("user_id");
            $name  = input("name");
            $user = Db::name("user")->where("id",$user_id)->find();
            if (empty($user)) {
                $this->error("用户信息信息不存在");
            }
            $data_template = [
                "thing1" => ["value" => $name],
                "thing2" => ["value" => $notes]
            ];

            (new WxApp)->sendMessage("MMBNC8ctxA8hEBmF-8X04nmq4N4e-dHn-srJlMtwsYc",$user["openid"],$data_template);


            $this->success("提交成功");
        } else{
            $this->error("提交失败");
        }
    }

    //添加心愿车源
    public function wish_add()
    {

        $params = input("post.");

        $params["updatetime"] = time();
        $params["createtime"] = time();
        $params["user_id"] = $this->auth->id;

        $result = Db::name("car_old_wish")->insert($params);

        if ($result) {
            $this->success("添加成功");
        } else{
            $this->error("添加失败");
        }
    }

    //心愿车源详情
    public function wish_detail()
    {

        $id= input("id");

        $result = Db::name("car_old_wish")->where("id",$id)->find();
        $this->success("",$result);
    }

    //心愿车源编辑
    public function wish_deit()
    {

        $params = input("post.");

        $params["updatetime"] = time();

        $result = Db::name("car_old_wish")->where("id",$params["id"])->where("user_id",$this->auth->id)->update($params);
        if ($result) {
            $this->success("添加成功");
        } else{
            $this->error("添加失败");
        }
    }

    //心愿列表
    public function wish_list() {

        //分页
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page-1)*$limit;
        $list = Db::name("car_old_wish")
            ->field("car_old_wish.drive_type,car_old_wish.id,car_brand_ids,car_series_ids,car_models_ids,car_age,odometer_km,use_character,gearbox,city,energy_type,car_level,FES,select_list,form,car_chuchang")
            ->where("user_id",$this->auth->id)
            ->order("id desc")
            ->limit("$offset,$limit")
            ->select();

        $this->success('请求成功',$list);
    }

    //心愿车源 删除
    public function wish_del()
    {

        $id= input("id");


        $result = Db::name("car_old_wish")->where("id",$id)->where("user_id",$this->auth->id)->delete();

        if ($result) {
            $this->success("删除成功");
        } else{
            $this->error("删除失败");
        }
    }

    //心愿车单 车源列表
    public function wish_car_old_list() {

        $list = $this->getCarOld();

        $user_id = input("user_id");
        if (!empty($user_id)) {
            $list = $list->where("user_id",$user_id);
        }
        //本人显示所有
        if ($this->auth->id == $user_id) {
            $status = input("status");
            if ($status != "") {
                $list = $list->where("status",$status);
            }

            $verify_status = input("verify_status");
            if ($verify_status != "") {
                $list = $list->where("verify_status",$verify_status);
            }

        } else {
            $list =  $list->where("status",1)
                ->where("trade_status",1)
                ->where("verify_status",1);
        }

        //排序
        $sort = input("sort");
        $order = input("order");
        if (empty($sort)){
            $sort = "id";
            $order = "desc";
        }
        //分页
        $limit = input("limit");
        if (empty($limit)) {
            $limit = 10;
        }
        $page = input("page");
        if (empty($page)) {
            $page = 1;
        }
        $offset = ($page-1)*$limit;


        $list =  $list->order($sort,$order)
//            ->limit("$offset,$limit")
            ->paginate($limit);
//        halt(Db::getLastSql());
        $this->success('请求成功',$list);
    }


    //超过60天车源自动下架 定时任务
    public function automatic_delisting() {
        $time = time();
        // 减去60天
        $newTimestamp = strtotime('-90 days', $time);
//        $list = Db::name("car_old")->where("createtime","<",$newTimestamp)->update(["status"=>"0"]);
        $list = Db::name("car_old")->field("id,user_id,car_models_name,createtime")->where("createtime","<",$newTimestamp)->where("status",1)->select();
        foreach ($list as $v) {
            Db::name("car_old")->where("id",$v["id"])->update(["status"=>0]);
            $data["title"] = "车源下架通知";
            $data["notice"] = "您的车源 “".$v["car_models_name"]."” 在平台发布超过90天，平台以为您自动下架。如确认车源暂未销售。可核对车源信息后。重新进行上传。";
            $data["createtime"] = time();
            $data["user_id"] = $v["user_id"];
            $data["car_old_id"] = $v["id"];
            Db::name("notice")->insert($data);

            $data_template = [
                "thing1" => ["value" => $v["car_models_name"]],
                "time2" => ["value" => date("Y-m-d H:i:s")],
                "thing3" => ["value" => "车源超过60天，自动下架"]
            ];
            $user = Db::name("user")->where("id", $v["user_id"])->find();
            (new WxApp)->sendMessage("4ojbvkc8Cp66JkjchOZ1GCGXQtV18NCnYtWD-2kFCD0", $user["openid"], $data_template);


        }

        $this->success('请求成功');

    }

    //超过15天圈子自动下架 定时任务
    public function circle_info_delisting() {
        $time = time();
        // 减去15天
        $newTimestamp = strtotime('-15 days', $time);
        $list = Db::name("circle_info")->where("createtime","<",$newTimestamp)->update(["status"=>"0"]);
        $this->success('请求成功',$list);

    }

}
